<template>
  <div class="uploadCom">
    <a-upload
      :list-type="!draggable ? listType : ''"
      :draggable="draggable"
      :limit="props.limit"
      :custom-request="customRequest"
      :file-list="fileList"
      @before-remove="beforeRemove"
      image-preview
    >
      <template #upload-button v-if="isSlot">
        <slot></slot>
      </template>      
    </a-upload>
  </div>
</template>

<script setup>
  import {ref, watch, toRaw, computed} from 'vue';
  import { updateFile } from '@/api/common';
  import { fileDomain } from '@/templateDir/utils/common';

  const fileList = ref([]);
  const emits = defineEmits(['update:modelValue', 'parentComCustomHandler']);
  const props = defineProps({
    listType: { // 文件的展示形式
      type: String,
      default: 'picture-card'
    },
    draggable: { // 是否是拖拽
      type: Boolean,
      default: false,
    },
    isSlot: {
      type: Boolean,
      default: false,
    },
    isLiveCustomHandler: {
      type: Boolean,
      default: false,
    },
    defaultFileList: {
      // 保持接口数据中的类型即可（也就是逗号隔开），在组件内部进行转换
      type: String,
      default: [],
    },
    limit: {
      type: Number,
      default: 100,
    },
  });

  const initTimes = ref(0)

  const initFileList = (str) => {
    fileList.value = [];
    if (str) {
      console.error(str);
      const arr = str.split(',');
      arr.forEach((element, index) => {
        fileList.value.push({
          url: element,
          name: element,
          uid: index,
        });
      });
    }
  };

  watch(
    () => props.defaultFileList,
    (n) => {
      if (n && initTimes.value < 1 && typeof props.defaultFileList === 'string') {
        initTimes.value++
        initFileList(props.defaultFileList);
      }
    },
    {
      immediate: true,
      deep: true
    }
  );

  watch(
    () => fileList,
    (n) => {
      const arr = toRaw(fileList.value);
      emits(
        'update:modelValue',
        (arr || []).map((v) => v.url)
      );
    },
    {
      deep: true,
    }
  );

  const beforeRemove = (file) => {
    return new Promise((resolve, reject) => {
      fileList.value.splice(
        fileList.value.findIndex(
          (v) => v.uid.toString() === file.uid.toString()
        ),
        1
      );
      reject('cancel'); // eslint-disable-line
    });
  };
  defineExpose({
    initFileList,
  });

  const customRequest = (option) => {
    const { onProgress, onError, onSuccess, fileItem, name } = option;

    const formData = new FormData();
    formData.append('file', fileItem.file);
    updateFile(formData)
      .then((res) => {
        const link = fileDomain + res?.data;
        fileList.value.push({
          url: link,
          name: link,
          uid: new Date().getTime(),
        });

        if (props.isLiveCustomHandler) {
          emits('parentComCustomHandler', {
            file: fileItem.file,
            url: link,
          });
        }
      })
      .catch((err) => {
        onError(err);
      });
  };
</script>

<style lang="less" scoped>
.uploadCom{
  flex: 1;
}
</style>
